import axios from 'axios'
import { ElMessage } from "element-plus";

export const service = axios.create({
  // baseURL: 'http://192.168.11.50:8080/jeecg-boot',
  baseURL: 'http://localhost:8080',
  // withCredentials: true,
  headers: {
    'Content-Type': 'multipart/form-data'
  },
  timeout: 30000
})

// 请求拦截器
service.interceptors.request.use((config: any) => {
  // 请求前做点什么
  const token = localStorage.getItem('token')
  console.log(token)
  if (token) {
    config.headers['X-Access-Token'] = token
  }
  return config
}, (error) => {
  return Promise.reject(error)
}
)

// 响应拦截器
service.interceptors.response.use(
  (response: any) => {
    const { status, data, message } = response
    if (data.token) {
      localStorage.setItem('token', data.token)
      localStorage.setItem('name', data.data.username)
    }
    if (status === 200) return data
    else if (status === 401) {
        jumpLogin()
      // 跳转去登陆界面
    } else {
      ElMessage.error(message)
      return Promise.reject(data);
    }
  }, (error) => {
    if (error.response) {
      if (error.response.status === 401) {
        jumpLogin()
      }
    }
    ElMessage.error(error?.response?.data?.message || "服务端异常")
    return Promise.reject(error)
  }
)


// const router = useRouter();
export const jumpLogin = () => {
  // 跳转登陆界面
  // 移除token
  // 跳转路由
//   router.push({ path: '/login' })
};